package com.ferry.wallpaper.controller;

import com.ferry.wallpaper.domain.User;
import com.ferry.wallpaper.domain.UserWall;
import com.ferry.wallpaper.domain.Wall;
import com.ferry.wallpaper.domain.view.BelongView;
import com.ferry.wallpaper.domain.view.MeView;
import com.ferry.wallpaper.domain.view.WallView;
import com.ferry.wallpaper.service.UserService;
import com.ferry.wallpaper.service.UserWallService;
import com.ferry.wallpaper.service.WallService;
import com.ferry.wallpaper.utils.DateUtils;
import com.ferry.wallpaper.utils.MeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Controller
public class MeController {

    @Autowired
    private UserService userService;

    @Autowired
    private UserWallService userWallService;

    @Autowired
    private WallService wallService;

    @GetMapping("/me")
    public String me(Model model, HttpSession session) {
        Object user = session.getAttribute("user");
        if (user instanceof User) {
            User ue = (User) user;
            User nu = userService.get(ue.getUserId());
            model.addAttribute("user",nu);
            MeView meView = new MeView();

            List<UserWall> userWalls = userWallService.get(nu.getUserId());

            List<BelongView> belongViews = new ArrayList<>();
            for (UserWall userWall : userWalls) {
                Wall wall = wallService.get(userWall.getWallId());

                belongViews.add(new BelongView(new WallView(wall),userWall, DateUtils.getDate(userWall.getTime())));
            }
            meView.setUserId(nu.getUserId());
            meView.setBelongViews(belongViews);
            meView.setInfo(nu.getUserProfile());
            meView.setLevel(MeUtils.getLevel(nu.getUserLevel()));
            meView.setNickname(nu.getUserNickname());
            meView.setSex(MeUtils.getSex(nu.getUserSex()));
            meView.setIconPath(nu.getUserAvatar()==null?"/img/head.jpg":nu.getUserAvatar());

            model.addAttribute("me",meView);
        }
        return "me";
    }


    @GetMapping("/sign/{id}")
    public String sign(@PathVariable Long id) {
        boolean sign = userService.sign(id);
        return "redirect:/me";
    }

    @PostMapping("/icon/{id}")
    public String modifyIcon(@PathVariable Long id, MultipartFile file) {
        try {
            userService.modifyIcon(id, file.getBytes(), file.getOriginalFilename());
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "redirect:/me";
    }
}
